<script>
export default {
  name: "DepartmentList",
  computed: {
    /*stateBoolean(val) {
      return val === 1;
    }*/
  },
  data() {
    return {
      queryInfo: {
        keyword: '',
        currentPage: 1,
        pageSize: 8
      },
      total: 0,
      departmentList: [
      ],
      listLoading: false,
      sels: [],
      editFormVisible: false,
      editFormRules: [
        {required: true, message: '请输入部门名称', trigger: 'blur'},
        {required: true, message: '请输入部门简介', trigger: 'blur'},
        {required: true, message: '请输入部门经理', trigger: 'blur'},
        {required: true, message: '请输入父级部门', trigger: 'blur'},
        {required: true, message: '请输入部门状态', trigger: 'blur'},
      ],
      editForm: {
        id: '',
        name: '',
        intro: '',
        createTime: '',
        updateTime: '',
        path: '',
        state: '',
        manager: {
          id: '',
          username: '',
        },
        parent: {
          id: '',
          name: ''
        }
      },
      editLoading: false,
      departmentTree: [],
      managerList: [],
    }
  },
  methods: {
    getDepartmentList() {
      this.$http.post("/department", this.queryInfo).then(res => {
        // console.log(res)
        if (res.data.success) {
          this.departmentList = res.data.data.list
          this.total = res.data.data.total
          /*this.$message({
            message: res.data.msg,
            type: "success",
            showClose: true
          })*/
        } else {
          this.$message({
            message: res.data.msg,
            type: "error",
            showClose: true
          })
        }
      }).catch(err => {
        this.$message({
          message: "请求异常",
          type: "error",
          showClose: true
        })
      }).finally(() => {
        this.listLoading = false;
      })
    },
    queryDepartment() {
      this.getDepartmentList();
    },
    handleAdd() {
      this.editFormVisible = true;
      this.editForm = {
        id: '',
        name: '',
        intro: '',
        createTime: '',
        updateTime: '',
        path: '',
        state: '',
        manager: {
          id: '',
          username: '',
        },
        parent: {
          id: '',
          name: ''
        }
      };
    },
    handleSizeChange(val) {
      this.queryInfo.pageSize = val;
      this.getDepartmentList();
    },
    selsChange(sels) {
      this.sels = sels
    },
    batchRemove() {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let ids = this.sels.map(item => item.id);
        // console.log(ids)
        this.$http.patch("/department", ids).then(res => {
          if (res.data.success) {
            this.$message({
              message: res.data.msg,
              type: "success",
              showClose: true
            })
            this.getDepartmentList();
          }
        }).catch(err => {
          this.$message({
            message: "请求异常",
            type: "error",
            showClose: true
          })
        }).finally(() => {
          this.listLoading = false;
        })
      }).catch(() => {

      });
    },
    handleCurrentChange(val) {
      this.queryInfo.currentPage = val;
      this.getDepartmentList();
    },
    handleEdit(index, row) {
      this.editFormVisible = true;
      this.queryEmployeeList();
      this.queryDepartmentTree(row.id);
      // this.editForm = row;
      /*
        这行代码的作用是创建一个新的对象，并将 `row` 对象的所有属性复制到新的对象中，
        然后将新的对象赋值给 `this.editForm`。
        在 JavaScript 中，`Object.assign(target, ...sources)`
        方法用于将所有可枚举的自有属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
        在这个例子中，`Object.assign({}, row)` 创建了一个新的对象，并将 `row` 对象的所有属性复制到新的对象中。
        然后，这个新的对象被赋值给 `this.editForm`。

        这样做的目的通常是为了避免直接修改原始数据 `row`，因为在 JavaScript 中，对象是通过引用传递的，
        如果你直接将 `row` 赋值给 `this.editForm`，
        那么当你修改 `this.editForm` 的时候，`row` 也会被修改。
        通过使用 `Object.assign` 创建一个新的对象，你可以避免这个问题。
      * */
      this.editForm = Object.assign({}, row);
      // console.log("编辑框==》》", this.editForm)
      if (!this.editForm.manager) {
        this.editForm.manager = {
          id: null,
          username: ''
        }
      }
      if (!this.editForm.parent) {
        this.editForm.parent = {
          id: null,
          name: ''
        }
      }
    },
    handleDel(index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/department/" + row.id).then(res => {
          if (res.data.success) {
            this.$message({
              message: res.data.msg,
              type: "success",
              showClose: true
            })
            this.getDepartmentList();
          }
        }).catch(err => {
          this.$message({
            message: "请求异常",
            type: "error",
            showClose: true
          })
        }).finally(() => {
          this.listLoading = false;
        })
      }).catch(() => {

      });
    },
    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.editLoading = true;
          // console.log("编辑款父部门==》》 ",this.editForm.parent);
          if (this.editForm.parent.id == null || this.editForm.parent.id.length === 0) {
            this.editForm.parent.id = null;
          } else {
            this.editForm.parent.id = this.editForm.parent.id[this.editForm.parent.id.length - 1];
          }
          // console.log("提交的数据==》》", this.editForm)
          this.$http.put("/department", this.editForm).then(res => {
            if (res.data.success) {
              this.editFormVisible = false;
              this.$message({
                message: res.data.msg,
                type: "success",
                showClose: true
              })
              this.getDepartmentList();
            }
          }).catch(err => {
            this.$message({
              message: "请求异常",
              type: "error",
              showClose: true
            })
          }).finally(() => {
            this.editLoading = false;
          })
        }
      })
    },
    queryDepartmentTree(id) {
      this.$http.get("/department/parents/" + id).then(res =>{
        if (res.data.success) {
          this.departmentTree = res.data.data;
        }
      }).catch(error => {
        this.$message({
          message: "父级部门列表获取失败",
          type: "error",
          showClose: true
        })
      })
    },
    queryEmployeeList() {
      this.$http.get("/employee").then(res => {
        if (res.data.success) {
          this.managerList = res.data.data;
        }
      }).catch(error => {
        this.$message({
          message: "部门经理列表获取失败",
          type: "error",
          showClose: true
        })
      })
    }
  },
  mounted() {
    this.getDepartmentList()
  }
}
</script>

<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="queryInfo.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryDepartment">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="departmentList" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              max-height="450px"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable/>
      <el-table-column prop="intro" label="简介" width="120" sortable/>
      <el-table-column prop="createTime" label="创建时间" width="160" sortable/>
      <el-table-column prop="updateTime" label="修改时间" width="160" sortable/>
      <el-table-column prop="manager.username" label="部门经理" width="120" sortable/>
      <el-table-column prop="parent.id" label="父级部门" width="100" sortable/>
      <el-table-column prop="state" label="状态" width="120" sortable>
        <template v-slot="scope">
          <el-tag v-if="scope.row.state === 1" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.state === 0" type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template v-slot="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="queryList.total" style="float:right;">
            </el-pagination>-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.currentPage"
          :page-sizes="[3, 5, 8, 10, 20]"
          :page-size="8"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog title="编辑" :close-on-click-modal="false" :visible.sync="editFormVisible">
<!--      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">-->
      <el-form :model="editForm" label-width="80px" ref="editForm">
        <el-form-item label="部门名称">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门简介" prop="intro">
          <el-input v-model="editForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门经理" prop="manager.username">
          <el-select v-model="editForm.manager.id" placeholder="请选择">
            <el-option
                v-for="item in managerList"
                :key="item.id"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.email }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="父级部门" prop="parent.name">
          <el-cascader
              :options="departmentTree"
              :props="{
              checkStrictly: true,
              value: 'id',
              label: 'name'
            }"
              v-model="editForm.parent.id"
              clearable></el-cascader>
        </el-form-item>
        <el-form-item label="部门状态" prop="state">
<!--          <el-input v-model="editForm.state" auto-complete="off"></el-input>-->
          <el-switch
              v-model="editForm.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="启用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="0">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--新增界面-->
    <!--    <el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
          <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="addForm.name" auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="addForm.sex">
                <el-radio class="radio" :label="1">男</el-radio>
                <el-radio class="radio" :label="0">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="年龄">
              <el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
            </el-form-item>
            <el-form-item label="生日">
              <el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>
            </el-form-item>
            <el-form-item label="地址">
              <el-input type="textarea" v-model="addForm.addr"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click.native="addFormVisible = false">取消</el-button>
            <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
          </div>
        </el-dialog>-->
  </section>
</template>

<style scoped>

</style>
